// src/common/util/halfScreen.ts
import Taro from '@tarojs/taro';

type EnvVersion = 'release' | 'trial' | 'develop';

const DEFAULTS = {
  appId: 'wxddc8369e7b9467c9', // 你的固定 appId（可按需改）
  envVersion: 'release' as EnvVersion,
  allowFullScreen: true,
  extraData: {} as Record<string, any>,
};

export type HalfScreenReturnReason = 'success' | 'fail' | 'close';

export interface HalfScreenCallbacks {
  /** 仅表示“半屏已成功拉起” */
  onOpen?: (res: any) => void;
  /** 拉起失败（参数非法/权限/用户取消等） */
  onFail?: (err: any) => void;
  /**
   * 关闭半屏返回到本小程序（统一出口）
   * reason:
   *  - success：从对方小程序回传了成功标记
   *  - fail：从对方回传了失败标记
   *  - close：未回传标记，通常为用户直接关闭（点“X”）
   */
  onReturn?: (payload: {
    reason: HalfScreenReturnReason;
    extraData?: any;
    fromAppId?: string;
    raw?: any; // 原始 onAppShow 参数
  }) => void;
}

/**
 * 半屏打开目标小程序（只有 path 必传）
 * 注意：最好在用户点击事件中同步调用。
 */
export async function halfScreenJump(
  path: string,
  cbs: HalfScreenCallbacks = {},
  // 可选覆盖 appId/envVersion/extraData；不传就用默认值
  opts?: Partial<{
    appId: string;
    envVersion: EnvVersion;
    extraData: Record<string, any>;
    allowFullScreen: boolean; // 仍允许覆盖，默认 true
  }>
) {
  if (!path) {
    const msg = '暂无商城信息，请稍后再试。';
    Taro.showToast({ title: msg, icon: 'none' });
    cbs.onFail?.(new Error(msg));
    return;
  }

  const appId = opts?.appId ?? DEFAULTS.appId;
  const envVersion = opts?.envVersion ?? DEFAULTS.envVersion;
  const extraData = opts?.extraData ?? DEFAULTS.extraData;
  const allowFullScreen =
    typeof opts?.allowFullScreen === 'boolean'
      ? opts.allowFullScreen
      : DEFAULTS.allowFullScreen;

  // 监听“返回本小程序”，当半屏关闭时触发
  const onShowOnce = (showOpts: any) => {
    Taro.offAppShow(onShowOnce);
    const ref = showOpts?.referrerInfo || {};
    const ex = ref?.extraData;

    // 轻量归一：根据常见字段推断是否成功
    const flag = ex?.result ?? ex?.status ?? ex?.code;
    let reason: HalfScreenReturnReason = 'close';
    if (flag === 'success' || flag === 'ok' || flag === true || flag === 0) {
      reason = 'success';
    } else if (flag === 'fail' || flag === false || flag === -1) {
      reason = 'fail';
    } // 否则视为 close

    cbs.onReturn?.({
      reason,
      extraData: ex,
      fromAppId: ref.appId,
      raw: showOpts,
    });
  };

  // 先挂监听，避免错过返回
  Taro.onAppShow(onShowOnce);

  try {
    await Taro.openEmbeddedMiniProgram({
      // 部分字段在旧基础库可能没类型提示，使用 as any 兼容
      ...(allowFullScreen ? ({ allowFullScreen } as any) : {}),
      appId,
      path,
      extraData,
      envVersion,
    } as any);

    // 成功拉起半屏
    cbs.onOpen?.({ ok: true });
  } catch (e: any) {
    // 打开失败：取消监听（不会返回 onAppShow 了）
    Taro.offAppShow(onShowOnce);
    const msg = String(e?.errMsg || '跳转失败，请稍后重试');
    Taro.showToast({ title: msg, icon: 'none' });
    cbs.onFail?.(e);
    console.error('openEmbeddedMiniProgram fail:', e);
  }
}
